import { handlerGobackClick, hint } from "../../../utils/util";
import { config } from "../../../config";
import { Base } from "../../../models/base";

const base = new Base();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    autoSize: { minHeight: 130 },
    message: "",
    fileList: [],
    arr: [
      {
        code: 1,
        name: "运行异常",
      },
      {
        code: 2,
        name: "咨询",
      },
      {
        code: 3,
        name: "意见",
      },
      {
        code: 0,
        name: "其他",
      },
    ],
    active: [false, false, false, false],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  handlerGobackClick,
  clickItem(e) {
    let index = e.currentTarget.dataset.index;
    let active = Object.assign([], this.data.active);
    active.forEach((item, index) => {
      active[index] = false;
    });

    active[index] = true;
    this.setData({
      active,
    });
  },
  afterRead(event) {
    const { file } = event.detail;
    let token = wx.getStorageSync("token");
    const that = this;

    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: config.baseUrl + "/mini/miniFeedback/uploadPics", // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: "file",
      header: {
        "Content-Type": "multipart/form-data",
        "X-Access-Token": token,
      },
      success(res) {
        // 上传完成需要更新 fileList
        let data = JSON.parse(res.data);
        const { fileList = [] } = that.data;
        fileList.push({ ...file, url: data.result });
        that.setData({ fileList });
      },
    });
  },
  deleteImg(e) {
    this.data.fileList.splice([e.detail.index], 1);
    this.setData({ fileList: this.data.fileList });
  },
  save() {
    let commid = wx.getStorageSync("commid");
    let arr = this.data.fileList.map((item, index) => {
      return item.url;
    });
    let pics = arr.join(",");
    let index;
    for (let i = 0; i < this.data.active.length; i++) {
      if (this.data.active[i]) {
        index = this.data.arr[i].code;
        break;
      }
    }
    if (index === undefined) {
      hint("请选择反馈类型！");
      return;
    }
    if (!this.data.message) {
      hint("请填写问题描述！");
      return;
    }
    base
      .feedback(pics, this.data.message, index, commid)
      .then((res) => {
        if (res.code == 1000) {
          hint("添加成功");
          setTimeout(() => {
            wx.navigateBack();
          }, 1000);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  },
  onChange(e) {
    this.setData({
      message: e.detail,
    });
  },
});
